package nsu.edu.zsq.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import nsu.edu.zsq.bean.Student;
import nsu.edu.zsq.bean.SysUser;
import nsu.edu.zsq.bean.Teacher;
import nsu.edu.zsq.common.RequestHolder;
import nsu.edu.zsq.util.UserType;

/** 
* Description: 登录的过滤器，对请求判断当前是否登录，没有登录则跳转到登录页面<br>
*/
@Slf4j
public class LoginFilter implements Filter{

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        
        String url = request.getRequestURI();
        Object user = session.getAttribute("user");
        if (user == null) {
            // 1.没有登录，则重定向到登录页
            log.info("请求的地址为：{}。没有登录，无法访问，跳转到登录页面", url);
            response.sendRedirect("/toLogin");
            return ;
        } else {
            // 2.已经登录，则保存用户信息和request到全局的RequestHolder中
            String userType = (String)session.getAttribute("userType");
            if (UserType.TYPE_STUDENT.equals(userType)) {
                // 学生登录
                Student student = (Student)user;
                RequestHolder.add(student);
            } else if (UserType.TYPE_TEACHER.equals(userType)) {
                // 教师登录
                Teacher teache = (Teacher)user;
                RequestHolder.add(teache);
            } else if (UserType.TYPE_SYSUSER.equals(userType)) {
                // 管理员登录
                SysUser sysUser = (SysUser)user;
                RequestHolder.add(sysUser);
            }
            RequestHolder.add(request);
        }
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

}
